package com.xiangwei.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class LocationUtils {
	/**
	 * 根据经纬度 获取位置
	 * 百度key   UGu5ORF0j4z75SaAgjPCcW28
	 * */
	public static Map<String,Object> getLngAndLat(String x,String y){
		Map<String,Object> map=new HashMap<String, Object>();
		String url = "http://api.map.baidu.com/geocoder/v2/?ak=UGu5ORF0j4z75SaAgjPCcW28"
				+ "&callback=renderReverse&location=X,Y&output=json&pois=1";
		String replace = url.replace("X", x).replace("Y", y);
		String json = loadJSON(replace);
		String string = json.replace("renderReverse&&renderReverse(", "").replace(")", "");
		JSONObject obj = (JSONObject) JSONObject.parse(string);
		if(obj.get("status").toString().equals("0")){
			String addr = obj.getJSONObject("result").getString("formatted_address");
			map.put("address", addr);
		}
		return map;
	}
	
	public static String loadJSON (String url) {
	       StringBuilder json = new StringBuilder();
	       try {
	           URL oracle = new URL(url);
	           URLConnection yc = oracle.openConnection();
	           BufferedReader in = new BufferedReader(new InputStreamReader(
	                                       yc.getInputStream(),"utf-8"));
	           String inputLine = null;
	           while ( (inputLine = in.readLine()) != null) {
	               json.append(inputLine);
	           }
	           in.close();
	       } catch (MalformedURLException e) {
	       } catch (IOException e) {
	       }
	       return json.toString();
	   }

	 public static void main(String[] args) throws Exception {
		 System.out.println(getLngAndLat("28.17259","113.0196"));
	 }
}
